package models.weixin.crop.bean;

import com.google.gson.*;
import me.chanjar.weixin.common.util.json.GsonHelper;

import java.lang.reflect.Type;

/**
 * Agent转换器.
 */
public class WxCpAgentGsonAdapter implements JsonSerializer<WxCpAgent>, JsonDeserializer<WxCpAgent> {
    @Override
    public WxCpAgent deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        JsonObject o = json.getAsJsonObject();
        WxCpAgent wxCpAgent = new WxCpAgent();
        wxCpAgent.id = GsonHelper.getString(o, "agentid");
        wxCpAgent.name = GsonHelper.getString(o, "name");
        wxCpAgent.squareLogoUrl = GsonHelper.getString(o, "square_logo_url");
        wxCpAgent.roundLogoUrl = GsonHelper.getString(o, "round_logo_url");
        wxCpAgent.appId = GsonHelper.getString(o, "appid");

        final JsonArray jsonApiGroupsArray = o.get("api_group").getAsJsonArray();
        wxCpAgent.apiGroup = new String[jsonApiGroupsArray.size()];
        for (int i = 0; i < wxCpAgent.apiGroup.length; i++) {
            final JsonElement jsonApiGroup = jsonApiGroupsArray.get(i);
            wxCpAgent.apiGroup[i] = jsonApiGroup.getAsString();
        }

        return wxCpAgent;
    }

    @Override
    public JsonElement serialize(WxCpAgent wxCpAgent, Type type, JsonSerializationContext jsonSerializationContext) {
        JsonObject o = new JsonObject();
        o.addProperty("agentid", wxCpAgent.id);
        o.addProperty("name", wxCpAgent.name);
        o.addProperty("square_logo_url", wxCpAgent.squareLogoUrl);
        o.addProperty("round_logo_url", wxCpAgent.roundLogoUrl);
        o.addProperty("appid", wxCpAgent.appId);
        return o;
    }
}
